import UserOutlined from "@ant-design/icons/UserOutlined"
import { User } from "@mallfoundry/keystone/identity"
import { DEFAULT_LIMIT, DEFAULT_PAGE } from "@mallfoundry/shared/data"
import { Store, StoreService } from "@mallfoundry/store"
import { StaffType } from "@mallfoundry/store/staff"
import { Alert, Avatar, Button, Card, Checkbox, Col, Descriptions, Divider, Empty, Modal, Pagination, Row, Tag } from "antd"
import classNames from "classnames"
import * as _ from "lodash"
import * as React from "react"
import { useState } from "react"
import { Link, useHistory } from "react-router-dom"
import Page from "../../components/page"
import { useStores } from "../../hooks/store"
import { useCurrentUser } from "../../hooks/user"

import classes from "./store-list.module.scss"

interface UserInfoProps {
  user: User
}

function UserInfo(props: UserInfoProps) {
  const { user } = props
  return (
    <Row align="middle" className={classes.userInfo}>
      <Col><Avatar size={48} src={user.avatar} icon={<UserOutlined/>}/></Col>
      <Col>
        <Row align="middle"><Col><h4>{user.nickname}</h4></Col></Row>
        <Row align="middle">
          <Col>+{user.countryCode}-{user.phone}</Col>
          <Col><Button type="link" size="small"><Link to="/logout">退出</Link></Button></Col>
        </Row>
      </Col>
    </Row>
  )
}

interface StoreInfoProps {
  store: Store;
  staffType: StaffType
  onCancelStore?: React.MouseEventHandler<HTMLElement>;
}

function StoreInfo(props: StoreInfoProps) {
  const { store, staffType, onCancelStore } = props
  const history = useHistory()
  const [actionsVisible, setActionsVisible] = useState(false)

  return (
    <Card size="small" className={classes.storeInfo}
          hoverable
          onMouseLeave={() => setActionsVisible(false)}
          onMouseEnter={() => setActionsVisible(true)}
          onClick={() => history.push(`/stores/${store.id}/dashboard`)}>
      <Descriptions column={1} title={store.name} size="small">
        <Descriptions.Item label="主体信息">未认证</Descriptions.Item>
        <Descriptions.Item label="主营类目">{store.industry}</Descriptions.Item>
        <Descriptions.Item className={classes.storeFooter}>

          <div className={classNames({
            [classes.storeActionsHidden]: !actionsVisible,
          })}>
            <Button type="link" size="small" onClick={e => {
              e.stopPropagation()
              history.push(`/stores/${store.id}/edit`)
            }}>修改</Button>
            {staffType === StaffType.Owner && <>
              <Divider type="vertical"/>
              <Button type="link" size="small" onClick={e => {
                e.stopPropagation()
                if (_.isFunction(onCancelStore)) {
                  onCancelStore(e)
                }
              }}>注销</Button>
            </>}
          </div>
          <div>
            {staffType === StaffType.Owner && <Tag color="red">店主</Tag>}
            {staffType === StaffType.Staff && <Tag color="red">员工</Tag>}
            <Tag color="red">商城</Tag>
          </div>
        </Descriptions.Item>
      </Descriptions>
    </Card>
  )
}

export default function StoreList() {
  const [cancelStoreModalVisible, setCancelStoreModalVisible] = useState(false)
  const [cancelStoreConfirmed, setCancelStoreConfirmed] = useState(false)
  const [cancelStoreLoading, setCancelStoreLoading] = useState(false)
  const [currentStore, setCurrentStore] = useState(new Store())
  const currentUser = useCurrentUser()
  const { id: userId } = currentUser
  const [{ page, limit }, setPageLimit] = useState({
    page: DEFAULT_PAGE,
    limit: DEFAULT_LIMIT,
  })

  const {
    loading,
    size: pageSize,
    totalSize,
    elements: stores,
    refresh: refreshStores,
  } = useStores({
    page, limit,
    staffIds: userId,
  })

  const chunkStores = _.chunk(stores, 3)

  function onCancelStore() {
    setCancelStoreLoading(true)
    const { id = "" } = currentStore
    StoreService
      .cancelStore(id)
      .then(() => {
        setCancelStoreModalVisible(false)
        setCancelStoreConfirmed(false)
      })
      .then(refreshStores)
      .finally(() => setCancelStoreLoading(false))
  }

  return (<div className={classes.root}>
    <Page.Header title="选择店铺" ghost={false}/>
    <Page.Content className={classes.content} loading={loading}>
      <Modal
        title="注销店铺"
        visible={cancelStoreModalVisible}
        okButtonProps={{ disabled: !cancelStoreConfirmed }}
        confirmLoading={cancelStoreLoading}
        onOk={onCancelStore}
        onCancel={() => setCancelStoreModalVisible(false)}>
        <Alert message="注销店铺，所有店铺相关信息丢失，店铺购买的应用和业务失效且不予退款，请谨慎操作！"
               type="error"
               style={{ marginBottom: "16px" }}/>
        <Checkbox checked={cancelStoreConfirmed}
                  onChange={e => setCancelStoreConfirmed(e.target.checked)}>已知晓删除店铺的风险，确定删除</Checkbox>
      </Modal>
      <Row gutter={[16, 16]} justify="space-between" align="middle" className={classes.contentHeader}>
        <Col>
          <UserInfo user={currentUser}/>
        </Col>
        <Col>
          <Button type="primary">
            <Link to="/stores/create">创建店铺</Link>
          </Button>
        </Col>
      </Row>
      <Row>
        <Col span={24}>
          <Card bordered={false} className={classes.innerContent}>
            {_.isEmpty(stores)
              ? <Empty className={classes.emptyStores}
                       imageStyle={{ height: 120 }}
                       description="暂无店铺"/>
              : <>
                {
                  _.map(chunkStores, (stores: Store[], index) =>
                    <Row gutter={[24, 24]} key={index}>
                      {
                        _.map(stores, (store: Store) => (
                          <Col key={store.id} span={8}>
                            <StoreInfo store={store}
                                       staffType={currentUser.id === store.ownerId ? StaffType.Owner : StaffType.Staff}
                                       onCancelStore={() => {
                                         setCurrentStore(store)
                                         setCancelStoreModalVisible(true)
                                       }}/>
                          </Col>
                        ))
                      }
                    </Row>,
                  )
                }
                <Row gutter={[24, 0]}>
                  <Col span={24}>
                    <Pagination
                      current={_.toNumber(page)}
                      pageSize={pageSize}
                      total={totalSize}
                      onChange={((page, limit) => setPageLimit({
                        page,
                        limit: _.isUndefined(limit) ? DEFAULT_LIMIT : limit,
                      }))}/>
                  </Col>
                </Row>
              </>}
          </Card>
        </Col>
      </Row>
    </Page.Content>
  </div>)
}
